﻿using Jint;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WorkFlowCore.Conditions;
using WorkFlowCore.Plugins;

namespace WorkFlowCore.Framework.Conditions
{
    [Condition("自定义 Javascript 条件处理器（基于 JavaScriptServices ）", "通过 js 方法解析条件， 具体传参需根据插件配置决定")]
    [PluginDescription("函数代码：function canAccept(input){/*中间这部分自定义js代码，目的是为了解析参数 */  return true;},input 为 json 格式（参考 ConditionInput） {Expression:string 表达式,WorkTask:object 当前流程实例,CurrentWorkStep:object 当前审批步骤}")]
    [PluginDescription("返回：函数返回一个 bool 值，表示是否通过")]
    public class DefaultJavascriptCondition : ICondition, IConfigurable
    {
        public bool CanAccept(ConditionInput input)
        {
            try
            {
                var engine = new Engine();

                var add = engine
                    .Execute(configureContext.OriginalParameters.Replace("{Expression}", input.Expression))
                    .GetValue("canAccept");

                var result = engine.Invoke("canAccept", input);

                return result.AsBoolean();
            }
            catch (Exception)
            {
                return false;
            }
        }

        ConfigureContext configureContext;
        public Task Configure(ConfigureContext configureContext)
        {
            this.configureContext = configureContext;
            return Task.CompletedTask;
        }
    }
}
